package org.tuoren.official.service.impl;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import org.dromara.easyes.core.conditions.select.LambdaEsQueryWrapper;
import org.springframework.stereotype.Service;
import org.tuoren.common.core.utils.StringUtils;
import org.tuoren.common.mybatis.core.page.PageQuery;
import org.tuoren.common.mybatis.core.page.TableDataInfo;
import org.tuoren.official.es.convert.SearchEsConvert;
import org.tuoren.official.es.domain.ProductEs;
import org.tuoren.official.es.domain.SearchResultEs;
import org.tuoren.official.es.domain.TNewsCenterES;
import org.tuoren.official.es.esmapper.ESNewsMapper;
import org.tuoren.official.es.esmapper.EsProductMapper;
import org.tuoren.official.service.IProductAndNewsESService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * 产品中心，新闻中心-ES搜索
 */
@RequiredArgsConstructor
@Service
public class ProductAndNewsESServiceImpl implements IProductAndNewsESService {

    private final EsProductMapper esProductMapper;
    private final ESNewsMapper esNewsMapper;

    @Override
    public TableDataInfo<SearchResultEs> searchAll(String keyword, PageQuery pageQuery) {
        List<SearchResultEs> allResults = new ArrayList<>();
        // 查询产品
        LambdaEsQueryWrapper<ProductEs> productWrapper = new LambdaEsQueryWrapper<>();
        if (StringUtils.isNotBlank(keyword)) {
            productWrapper.and(iwrapper ->
                iwrapper.like(ProductEs::getName, keyword.toLowerCase())
                    .or()
                    .like(ProductEs::getDescribes, keyword.toLowerCase())
                    .or()
                    .like(ProductEs::getSummary, keyword.toLowerCase()));
        }
        List<ProductEs> productList = esProductMapper.selectList(productWrapper);
        Long l = esProductMapper.selectCount(productWrapper);
        System.out.println(l);
        System.out.println(JSONObject.toJSONString(productList));
        List<SearchResultEs> productResults = productList.stream()
            .map(SearchEsConvert.INSTANCE::toProduct)
            .collect(Collectors.toList());
        allResults.addAll(productResults);
        // 查询新闻
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        LambdaEsQueryWrapper<TNewsCenterES> newsWrapper = new LambdaEsQueryWrapper<>();
        if (StringUtils.isNotBlank(keyword)) {
            newsWrapper.and(iwrapper ->
                iwrapper.like(TNewsCenterES::getTitle, keyword.toLowerCase())
                    .or()
                    .like(TNewsCenterES::getNewDesc, keyword.toLowerCase())
                    .or()
                    .like(TNewsCenterES::getContent, keyword.toLowerCase())
                    .or()
                    .like(TNewsCenterES::getSource, keyword.toLowerCase()));
        }
        List<TNewsCenterES> newsList = esNewsMapper.selectList(newsWrapper);
        Long m = esNewsMapper.selectCount(newsWrapper);
        System.out.println(m);
        System.out.println(JSONObject.toJSONString(newsList));
        List<SearchResultEs> newsResults = newsList.stream()
            .map(SearchEsConvert.INSTANCE::toNews)
            .collect(Collectors.toList());
        List<SearchResultEs> list = newsResults.stream().map(newsResult -> {
            newsResult.setPublishDateFormat(dateFormat.format(newsResult.getPublishDate()));
            return newsResult;
        }).collect(Collectors.toList());
        allResults.addAll(list);
        // 按发布时间降序排序
        allResults.sort((a, b) -> {
            if ("news".equals(a.getType()) && "news".equals(b.getType())) {
                return b.getPublishDate().compareTo(a.getPublishDate());
            } else if ("news".equals(a.getType())) {
                return -1;
            } else {
                return 1;
            }
        });
        // 分页处理
        int total = allResults.size();
        int pageNum = pageQuery.getPageNum();
        int pageSize = pageQuery.getPageSize();
        int start = Math.min((pageNum - 1) * pageSize, total);
        int end = Math.min(start + pageSize, total);
        List<SearchResultEs> pagedList = allResults.subList(start, end);
        // 返回结果
        TableDataInfo<SearchResultEs> result = new TableDataInfo<>(pagedList, total);
        result.setCode(HttpStatus.HTTP_OK);
        result.setMsg("查询成功");
        return result;
    }
}
